package com.ruoyi.goods.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.goods.domain.BmSpecification;
import com.ruoyi.goods.service.SellerBrandService;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.goods.mapper.BmGoodsMapper;
import com.ruoyi.goods.domain.BmGoods;
import com.ruoyi.goods.service.IBmGoodsService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 商品信息管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-08-02
 */
@Service
public class BmGoodsServiceImpl implements IBmGoodsService 
{
    @Autowired
    private BmGoodsMapper bmGoodsMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private SellerBrandService sellerBrandService;
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 查询商品信息管理
     * 
     * @param id 商品信息管理主键
     * @return 商品信息管理
     */
    @Override
    public BmGoods selectBmGoodsById(Long id)
    {
        System.out.println("id="+id);
        return bmGoodsMapper.selectBmGoodsById(id);
    }

    /**
     * 查询商品信息管理列表
     * 
     * @param bmGoods 商品信息管理
     * @return 商品信息管理
     */
    @Override
    public List<BmGoods> selectBmGoodsList(BmGoods bmGoods)
    {
        List<BmGoods> goodsList = bmGoodsMapper.selectBmGoodsList(bmGoods);
        System.out.println("goodsList = " + goodsList);
        for (BmGoods goods : goodsList) {
            String goodsName = goods.getGoodsName();
            List<BmSpecification> bmSpecificationList = goods.getBmSpecificationList();
            System.out.println("----"+bmSpecificationList);
            if (bmSpecificationList != null) {
                StringBuilder sb = new StringBuilder(goodsName);
                for (BmSpecification bmSpecification : bmSpecificationList) {
                    String specificationName = bmSpecification.getSpecificationName();
                    // 将规格名称拼接到商品名称上
                    sb.append(" ").append(specificationName);
                }
                // 更新商品名称
                goods.setGoodsName(sb.toString());
            }
        }
        return goodsList;
//        return bmGoodsMapper.selectBmGoodsList(bmGoods);
    }

    /**
     * 新增商品信息管理
     * 
     * @param bmGoods 商品信息管理
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertBmGoods(BmGoods bmGoods) {
        String warehouseCode = bmGoods.getWarehouseCode();
        String goodsCode = "C" + warehouseCode + bmGoods.getGoodsCode();
        bmGoods.setGoodsCode(goodsCode); // 设置计算后的goods_code
        bmGoods.setCreateTime(DateUtils.getNowDate());
        int num1 = bmGoodsMapper.insertBmGoods(bmGoods);

        int num2=0;
        Long id = bmGoods.getId();
        for (int i = 0; i < bmGoods.getBmSpecificationList().size(); i++) {
            BmSpecification bmSpecification = bmGoods.getBmSpecificationList().get(i);
            bmSpecification.setGoodsId(id);
        }
        if(bmGoods.getBmSpecificationList()!=null && !bmGoods.getBmSpecificationList().isEmpty()){
            num2 = bmGoodsMapper.insertSpecification(bmGoods.getBmSpecificationList());
        }
        return num1 > 0 && num2 > 0 ? 1 : 0;
    }

    /**
     * 修改商品信息管理
     * 
     * @param bmGoods 商品信息管理
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateBmGoods(BmGoods bmGoods) throws IOException {
        List<BmSpecification> newSpecifications = bmGoods.getBmSpecificationList(); // 获取新的规格列表
//        // 更新BmGoods对象之前，先将新的BmSpecificationList设置到BmGoods对象中
        bmGoods.setBmSpecificationList(newSpecifications);
        int num1 = bmGoodsMapper.updateBmGoods(bmGoods);
        Long id = bmGoods.getId();
        int num2=0;
        DeleteRequest deleteRequest=null;
        IndexRequest indexRequest=null;
        for (BmSpecification newSpec : newSpecifications) {
            newSpec.setGoodsId(id);
            int count = bmGoodsMapper.selectSpecificationCountById(newSpec.getId());
            if (count == 0) { // 只处理新添加的规格数据
                num2 = bmGoodsMapper.addSpecification(newSpec);
            }else{
                num2 = bmGoodsMapper.updateSpecification(newSpec);
            }
            //先删除elasticsearch中存储的数据
            Long specificationId = newSpec.getId();
            deleteRequest=new DeleteRequest("goods",specificationId.toString());
            restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
            deleteRequest=new DeleteRequest("recommondgoods",specificationId.toString());
            restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
            //再录入修改后的数据
            Map<String,Object> map=new HashMap<>();
            map.put("specificationId",specificationId);
            List<Map<String, Object>> goodsList = bmGoodsMapper.findGoodsByCategory(map);
            for (Map<String, Object> good : goodsList) {
                //添加所有商品
                indexRequest=new IndexRequest("goods");
                indexRequest.source("{\"mappings\":{\"_source\":{\"enabled\":true}}}", XContentType.JSON);
                indexRequest.id(good.get("specificationId")+"").source(good, XContentType.JSON);
                restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
                //添加推荐商品
                if (Integer.parseInt(good.get("isRecommond").toString())==1){
                    indexRequest=new IndexRequest("recommondgoods");
                    indexRequest.source("{\"mappings\":{\"_source\":{\"enabled\":true}}}", XContentType.JSON);
                    indexRequest.id(good.get("specificationId")+"").source(good, XContentType.JSON);
                    restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
                }
            }
        }
        return num1 > 0 && num2 > 0 ? 1 : 0;
    }

    /**
     * 批量删除商品信息管理
     * 
     * @param ids 需要删除的商品信息管理主键
     * @return 结果
     */
    @Override
    public int deleteBmGoodsByIds(Long[] ids)
    {
        return bmGoodsMapper.deleteBmGoodsByIds(ids);
    }

    @Override
    public int deleteBmGoodsBySpecificationId(Long id) {
        return bmGoodsMapper.deleteBmGoodsBySpecificationId(id);
    }

    /**
     * 删除商品信息管理信息
     * 
     * @param id 商品信息管理主键
     * @return 结果
     */
    @Override
    public int deleteBmGoodsById(Long id)
    {
        return bmGoodsMapper.deleteBmGoodsById(id);
    }

    /**
     * 得到最大商品代码
     * @return
     */

    @Override
    public String getMaxGoodsCode() {
        return bmGoodsMapper.getMaxGoodsCode();
    }
    /**
     * 通过仓库编号得到商品数量
     * @return
     */
    @Override
    public int getGoodsNumByWarehouseCode(String warehouseCode) {
        return bmGoodsMapper.getGoodsNumByWarehouseCode(warehouseCode);
    }

    /**
     * 根据类别查询商品
     */
    @Override
    public List<Map<String, Object>> findGoodsByCategory(Map<String, Object> map) {
        return bmGoodsMapper.findGoodsByCategory(map);
    }

    /**
     * 添加购物车
     * @param good
     */
    @Override
    public void addCartGoods(Map<String, Object> good) {
        int specificationId = Integer.parseInt(good.get("specificationId").toString());
        if (Integer.parseInt(good.get("buyNum").toString())>0){
            redisService.setCacheMapValue("member" + 32, "goodsSpecificationId" + specificationId,good);
        }else {
            redisService.deleteCacheMapValue("member" + 32, "goodsSpecificationId" + specificationId);
        }
//        Map<String, Object> redisGood = redisService.getCacheMapValue("member" + 32, "goodsSpecificationId" + specificationId);
//        if (redisGood==null){
//            redisService.setCacheMapValue("member" + 32, "goodsSpecificationId" + specificationId,good);
//        }else {
//            redisService.setCacheMapValue("member" + 32, "goodsSpecificationId");
//        }
    }

    @Override
    public int selectCartNum(Map<String, Object> good) {
        int specificationId = Integer.parseInt(good.get("specificationId").toString());
        Map<String,Object> map=redisService.getCacheMapValue("member" + 32, "goodsSpecificationId" + specificationId);
        int buyNum=0;
        if (map!=null){
            buyNum = Integer.parseInt(map.get("buyNum").toString());
        }
        return buyNum;
    }

    @Override
    public List<Map<String, Object>> findAllGoods() throws IOException {
        //加载所有商品到索引
        List<Map<String, Object>> goodsList = bmGoodsMapper.findGoodsByCategory(null);
        for (Map<String, Object> good : goodsList) {
            IndexRequest indexRequest=new IndexRequest("goods");
            indexRequest.source("{\"mappings\":{\"_source\":{\"enabled\":true}}}", XContentType.JSON);
            indexRequest.id(good.get("specificationId")+"").source(good, XContentType.JSON);
            IndexResponse indexResponse= restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        }
        //加载推荐商品到索引
        Map map=new HashMap<>();
        map.put("isRecommond",1);
        List<Map<String,Object>> recommondGoods = bmGoodsMapper.findGoodsByCategory(map);
        for (Map<String, Object> recommondGood : recommondGoods) {
            IndexRequest indexRequest=new IndexRequest("recommondgoods");
            indexRequest.source("{\"mappings\":{\"_source\":{\"enabled\":true}}}", XContentType.JSON);
            indexRequest.id(recommondGood.get("specificationId")+"").source(recommondGood, XContentType.JSON);
            IndexResponse indexResponse= restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        }

        return goodsList;
    }

    @Override
    public List<Map<String, Object>> findGoodsByBnameOrGoodsName(Map<String,Object> map) throws IOException {
        if (map.get("brandId")==null || map.get("brandId")==""){
            //用来封装检索条件
            SearchRequest searchRequest=null;
            if (map.get("isRecommond")==null || map.get("isRecommond")==""){
                searchRequest=new SearchRequest("goods");
            }else {
                searchRequest=new SearchRequest("recommondgoods");
            }
            //查询条件
            SearchSourceBuilder searchSourceBuilder =new SearchSourceBuilder();
            System.out.println(map.get("bnameOrGoodsName"));
            if (map.get("bnameOrGoodsName")!=null && map.get("bnameOrGoodsName")!=""){
                searchSourceBuilder.query(QueryBuilders.multiMatchQuery(map.get("bnameOrGoodsName"),"bname", "goodsName"));
            }
            searchRequest.source(searchSourceBuilder);

            //执行检索
            SearchResponse searchResponse =restHighLevelClient.search(searchRequest,RequestOptions.DEFAULT);

            SearchHits hits = searchResponse.getHits();
            List<Map<String,Object>> goods =new ArrayList<>();
            for (SearchHit hit : hits) {
                Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                goods.add(sourceAsMap);
            }
            return goods;
        }else {
            List<Map<String, Object>> list = sellerBrandService.getList(map);
            return list;
        }
    }

    @Override
    public List<Map<String, Object>> addGoodsList() {
        return bmGoodsMapper.addGoodsList();
    }
}
